#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

void task1() {
    printf("task is running...\n");
}

void task2() {
    printf("task is runnning...\n");
}

int main() {
    int id = fork();
    if(id == 0) {  //子进程
        int cnt = 5;
        while(cnt--) {
            printf("子进程, pid:%d, ppid:%d, cnt:%d\n", getpid(), getppid(), cnt);
            sleep(1);
        }
        exit(1);
    } else {  //父进程
        int status = 0;
        while(1) {  //轮询
            pid_t ret = waitpid(id, &status, WNOHANG);  //非阻塞式等待
            if(ret == 0){  //调用成功，但子进程未退出
                printf("等待成功，但子进程未退出\n");
                task1();  //执行其他命令
                task2();
            } else {  //调用成功，子进程退出
                printf("等待成功，子进程退出\n");
                break;
            }
            sleep(1);
        }

        if(WIFEXITED(status)) {  //正常退出
            printf("exit code:%d\n", WEXITSTATUS(status));
        } else {  //异常终止
            printf("exit signal:%d\n",WIFEXITED(status));
        }
        
    }
    return 0;
}
